import 'package:flutter_baselib/flutter_baselib.dart';
import 'package:baselib_demo/common/manager/login_info_manager.dart';
import 'package:baselib_demo/common/net/util/http_json_utils.dart';
import 'package:baselib_demo/common/net/util/http_utils.dart';
import 'package:baselib_demo/module/login/bean/login_result_bean.dart';

import '../http_const.dart';
import '../http_urls.dart';

///@date:  2021/2/25 14:22
///@author:  lixu
///@description: http拦截器，添加请求头和通用参数
///TODO 修改通用参数
class HeaderInterceptor extends InterceptorsWrapper {
  String _tag = 'HeaderInterceptor';

  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) async {
    LogUtils.d(_tag, 'onRequest()');

    ///通用参数
    var params = {
      'lang': 'zhcn',
      'centerId': loginInfo.getCenterId(),
    };

    ///通过请求参数生成sign
    String sign;
    if (XApi.methodGet == options.method) {
      options.queryParameters = (Map<String, dynamic>.from(options.queryParameters))..addAll(params);
      sign = await HttpUtils.getSignEncode(options.queryParameters, HttpConst.serverKey);
    } else {
      options.data = (Map<String, dynamic>.from(options.data ?? {}))..addAll(params);
      sign = await HttpUtils.getSignEncode(options.data, HttpConst.serverKey);
    }

    ///添加请求头
    Map<String, String?> headerMap = loginInfo.token != null ? {'token': loginInfo.token} : {};
    headerMap.putIfAbsent('sign', () => sign);

    options.headers.addAll(headerMap);

    super.onRequest(options, handler);
  }

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) async {
    ///从登录接口中获取token和用户信息
    ///TODO 也可以直接在登录响应的对象中获取用户信息和token，此处只是演示http拦截器功能
    if (response.requestOptions.path.contains(HttpUrls.loginUrl)) {
      HttpResultBean<LoginResultBean> resultBean = await HttpJsonUtils.parseJsonToObject(HttpUrls.loginUrl, response.data, false);
      if (resultBean.isSuccess()) {
        loginInfo.token = resultBean.data?.token;
        loginInfo.userBean = resultBean.data?.user;
      }
      LogUtils.i(_tag, '登录获取的token：${loginInfo.token}');
    }
    super.onResponse(response, handler);
  }
}
